package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"time"

	"github.com/elastic/go-elasticsearch/v8"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"

	els "mxshop_srvs/goods_srv/dao/elasticsearch"
	"mxshop_srvs/goods_srv/model"
	"mxshop_srvs/goods_srv/setting"
)

var (
	db *gorm.DB
	es *elasticsearch.Client
)

func main() {
	setting.Init()

	InitGorm()

	// // 迁移 schema
	// _ = db.AutoMigrate(
	// 	&model.Category{},
	// 	&model.Brands{},
	// 	&model.GoodsCategoryBrand{},
	// 	&model.Banner{},
	// 	&model.Goods{},
	// )

	var (
		esConf = setting.Conf.ESConfig
		err    error
	)
	es, err = els.Init([]string{fmt.Sprintf("http://%s:%d", esConf.Host, esConf.Port)})
	if err != nil {
		return
	}

	SyncToES()
}

func InitGorm() {
	conf := setting.Conf.MysqlConfig
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		conf.User, conf.Password, conf.Host, conf.Port, conf.Database)

	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold: time.Second, // 慢 SQL 阈值
			LogLevel:      logger.Info, // Log level
			Colorful:      true,        // 禁用彩色打印
		},
	)

	// 全局模式
	var err error
	db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
		Logger: newLogger,
	})
	if err != nil {
		panic(err)
	}
}

func SyncToES() {
	var goodsSlice []model.Goods
	db.Find(&goodsSlice)

	c := context.Background()
	goodsES, err := els.NewGoodsES(c, es)
	if err != nil {
		panic(err)
	}

	for _, goods := range goodsSlice {
		esGoods := model.ESGoods{
			ID:          goods.ID,
			CategoryID:  goods.CategoryID,
			BrandsID:    goods.BrandsID,
			OnSale:      goods.OnSale,
			ShipFree:    goods.ShipFree,
			IsNew:       goods.IsNew,
			IsHot:       goods.IsHot,
			Name:        goods.Name,
			ClickNum:    goods.ClickNum,
			SoldNum:     goods.SoldNum,
			FavNum:      goods.FavNum,
			MarketPrice: goods.MarketPrice,
			GoodsBrief:  goods.GoodsBrief,
			ShopPrice:   goods.ShopPrice,
		}
		err := goodsES.Insert(c, esGoods.GetIndexName(), esGoods)
		if err != nil {
			fmt.Println(err.Error())
			<-time.After(3 * time.Second)
		}
	}
}
